/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.analyze.preview;

import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.component.spreadsheet.analyze.preview.UnitEvalPreviewSheetView;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.UnitEvaluationViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.AppUtils;
import cn.ac.nercis.pes.community.utils.LogUtils;
import cn.ac.nercis.pes.community.utils.SpringUtils;
import cn.ac.nercis.pes.service.evaluation.UnitEvaluationService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * 单元测评预览控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class UnitEvalPreviewController implements Initializable {

    @FXML
    private UnitEvalPreviewSheetView sheetView;

    private final UnitEvaluationService unitEvaluationService;
    private final ExecutorService executor;

    private String currentSystemId;
    private MenuVO currentLayerTarget;
    private StackPane page;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    public UnitEvalPreviewController() {
        this.unitEvaluationService = SpringUtils.getBean(UnitEvaluationService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    public void initializeData(String systemId, MenuVO layerTarget, StackPane page) {
        LogUtils.info(log, "初始化单元测评预览内容...");
        this.currentSystemId = systemId;
        this.currentLayerTarget = layerTarget;
        this.page = page;
        loadUnitEvaluation();
    }

    public void realTimeSave() {
        LogUtils.info(log, "执行即时保存操作...");
        batchSaveUnitEvaluation();
    }

    private void batchSaveUnitEvaluation() {
        var modifyData = this.sheetView.getModifyData().stream()
                .map(UnitEvaluationViewMapper.INSTANCE::toDTO)
                .toList();
        if (CollectionUtils.isEmpty(modifyData)) {
            AppUtils.showMessageDialog("保存成功", MessageType.SUCCESS, this.page);
            return;
        }
        LogUtils.info(log, "批量保存单元预览信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, modifyData);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.unitEvaluationService.batchSaveUnitEvaluation(modifyData), this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        //更新表数据
                        this.loadUnitEvaluation();
                    } else {
                        AppUtils.showMessageDialog(res.getMsg(), MessageType.FAIL, this.page);

                    }
                }))
                .exceptionally((ex) -> {
                    log.error("批量保存单元预览信息出错!", ex);
                    return null;
                });
    }

    private void loadUnitEvaluation() {
        LogUtils.info(log, "获取单元测评预览内容...");
        LogUtils.record(log, "请求数据，systemId：{},unitTargetId:{}", this.currentSystemId, currentLayerTarget.getCode());
        CompletableFuture.supplyAsync(() -> unitEvaluationService.findUnitEvaluationByLayerTarget(this.currentSystemId
                        , currentLayerTarget.getCode()), this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        var sheetData = res.getData().stream().map(UnitEvaluationViewMapper.INSTANCE::toVO).toList();
                        this.sheetView.loadContent(sheetData);
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取单元测评预览内容出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

}